from ctypes import c_ubyte

import cairo
import pyglet
from pyglet.gl import *

from singleton import Singleton

class CairoImage():
    def __init__(self, w, h):
        self.w = w
        self.h = h
        
        self.data = (c_ubyte * w * h * 4)()
        self.surf = cairo.ImageSurface.create_for_data(self.data,
                                           cairo.FORMAT_ARGB32, w, h, w * 4)
        self.ctx = cairo.Context(self.surf)
        
        self.texture = pyglet.image.Texture.create_for_size(GL_TEXTURE_2D,
                                                            w, h, GL_RGBA)
        
        self.quad = pyglet.graphics.vertex_list(4,
                                           ('v2f', (0, 0, w, 0, w, h, 0, h)),
                                           ('t2f', (0, 0, 1, 0, 1, 1, 0, 1)),
                                           ('c3B', (255, 255, 255) * 4),
                                          )
    
    def setQuad(self, x, y, w, h):
        self.quad.vertices = [x, y, w, y, w, h, x, h]
    
    def draw(self):
        glEnable(GL_TEXTURE_2D)
        glBindTexture(GL_TEXTURE_2D, self.texture.id)
        
        #Use the data from the Cairo surface as texture
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, self.w, self.h, 0, GL_BGRA,
                     GL_UNSIGNED_BYTE, self.data)
        
        self.quad.draw(GL_QUADS)

def test(ctx, m=50, n=80):
    ctx.set_source_rgb(0, 0, 0)
    ctx.paint()
    
    ctx.set_line_width(0.001)
    ctx.set_source_rgb(255, 0, 0)
    for i in range(m):
        ctx.move_to(0.0, -0.25)
        ctx.line_to(0.25, 0.25)
        ctx.rel_line_to(-0.5, 0.0)
        for i in range(n):
            ctx.rel_line_to(0.005 * (i % 5), 0.01 * (1-(i % 3)))
        ctx.close_path()
        ctx.stroke()
        
        ctx.rotate(0.02)
    
    ctx.rotate(-0.02 * (m - 1))